package com.ycsj.goldmedalnewconcept.master.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.squareup.picasso.Picasso;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropActivity;
import com.ycsj.common.utils.SPUtil;
import com.ycsj.common.utils.UiUtils;
import com.ycsj.goldmedalnewconcept.R;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.PicassoEngine;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 模板预览界面
 */

public class SkinListActivity extends Activity implements View.OnClickListener {

    // 返回
    private LinearLayout llBack;

    // 保存
    private TextView tvSave;

    private ImageView lvCenterTop;

    // 加载框
    private LinearLayout llLoading;

    protected static final int THEME_ID = 0;

    // 三张图片的ImageView
    private ImageView lvTop, lvCenter, lvBottom;

    private String top;

    private String center;

    private String bottom;

    private FrameLayout fl;

    private RelativeLayout rlCenter;

    // 拍照的请求码
    public static final int CAMERA_REQUEST_CODE = 0X108;

    private static final int REQUEST_CODE_CHOOSE = 23;//定义请求码常量

    private String imagePath;

    private String themeId;

    // 弹框选择相关
    private View view;

    private TextView tvCamera;

    private TextView tvPic;

    private TextView tvCancel;

    private PopupWindow popupWindow;

    protected static Uri tempUri;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_skin_list);

        // 设置状态栏颜色
        setBar();

        // 初始化控件
        initViews();

        // 获取上中下三张图片信息
        initIntent();

        // 设置监听
        initListener();

        // 设置图片数据
        setData();
    }

    /**
     * 初始化控件的方法
     */
    private void initViews() {
        // 获取屏幕宽度
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        int screenHeight = wm.getDefaultDisplay().getHeight();

        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, screenHeight / 3);

        llBack = findViewById(R.id.ll_back);
        tvSave = findViewById(R.id.tv_save);
        lvTop = findViewById(R.id.lv_top);
        lvCenter = findViewById(R.id.lv_center);
        lvBottom = findViewById(R.id.lv_bottom);
        fl = findViewById(R.id.fl_center);
        lvCenterTop = findViewById(R.id.lv_center_top);
        rlCenter = findViewById(R.id.rl_center);
        lvTop.setLayoutParams(lp);
        fl.setLayoutParams(lp);
        lvBottom.setLayoutParams(lp);

    }

    /**
     * 获取页面传递过来的数据
     */
    private void initIntent() {
        Intent intent = getIntent();
        top = intent.getStringExtra("top");
        center = intent.getStringExtra("center");
        Log.i("test", "中间图片的值是:" + center);
        bottom = intent.getStringExtra("bottom");
        themeId = intent.getStringExtra("themeId");
    }

    /**
     * 设置三张图片数据
     */
    private void setData() {
        if (llLoading != null) {
            llLoading.setVisibility(llLoading.GONE);
        }
        Picasso.with(SkinListActivity.this).load(top).error(R.drawable.defaultimage).into(lvTop);
        Picasso.with(SkinListActivity.this).load(center).error(R.drawable.defaultimage)
                .into(lvCenter);
        Picasso.with(SkinListActivity.this).load(bottom).error(R.drawable.down).into(lvBottom);
    }

    /**
     * 设置监听的方法
     */
    private void initListener() {
        llBack.setOnClickListener(this);
        tvSave.setOnClickListener(this);
        rlCenter.setOnClickListener(this);
    }

    /**
     * 设置沉浸状态栏的方法,需要在setContentView()之后调用
     */
    @SuppressLint("NewApi")
    private void setBar() {
        // 兼容5.0+，状态栏设置透明
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else
            // 为了沉浸式状态栏 4.4以上才有
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                getWindow().addFlags(
                        WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            }
    }


    /**
     * 页面控件点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_back:
                // 返回
                finish();
                break;
            case R.id.tv_save:
                // 保存
                Intent mIntent = new Intent(this, MasterCreatRedPackageActivity.class);
                SPUtil.put(this, "imagePath", imagePath);
                SPUtil.put(this, "themeId", themeId);
                // 设置结果，并进行传送
                startActivity(mIntent);
                ToastUtils.showShort("模板保存成功");
                finish();
                break;
            case R.id.rl_center:
                // 点击中间图片弹框操作
                showPopUpWindow();
                break;
            case R.id.tv_camera:
                // 选择拍照
                doCameraAction();
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                    view = null;
                }
                break;
            case R.id.tv_pic:
                // 选择相册
                try {
                    showChoosePic();

                    if (popupWindow != null && popupWindow.isShowing()) {
                        popupWindow.dismiss();
                        view = null;
                    }
                } catch (Exception e) {
                    Log.e("error", "error" + e.toString());
                }
                break;
            case R.id.tv_cancel:
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                    view = null;
                }
                break;
        }
    }


    /**
     * 调用相册
     */
    private void showChoosePic() {
        Matisse
                .from(SkinListActivity.this)
                .choose(MimeType.ofImage())//照片视频全部显示
                .countable(true)//有序选择图片
                .maxSelectable(1)//最大选择数量为9
                .gridExpectedSize(UiUtils.dp2px(120))//图片显示表格的大小getResources()
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)//图像选择和预览活动所需的方向。
//                .thumbnailScale(0.85f)//缩放比例
                .theme(R.style.Matisse_Dracula)//主题  暗色主题 R.style.Matisse_Dracula
                .imageEngine(new PicassoEngine())//加载方式
                .forResult(REQUEST_CODE_CHOOSE);//请求码
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_CHOOSE) {

                //相册选择图片后调用裁剪
                List<Uri> uris = Matisse.obtainResult(data);
                startCrop(uris.get(0));

            } else if (requestCode == CAMERA_REQUEST_CODE) {

                // 相机调用裁剪功能
                startCrop(tempUri);

            } else if (requestCode == UCrop.REQUEST_CROP) {
                //获取裁剪后的Uri
                Uri resultUri = UCrop.getOutput(data);

                Bitmap bitmap = null;
                if (resultUri != null) {
                    try {
                        bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), resultUri);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                // 获取调用原生裁剪功能后的图片地址,只能获取到Bitmap对象
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
                        "yyyyMMddHHmmss");
                Date date = new Date();
                String imageName = simpleDateFormat.format(date);
                imagePath = imageName;
                // 获取文件的地址用于生成文件
                try {
                    saveFile(bitmap, imagePath + ".png");
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                lvCenterTop.setImageURI(null);
                lvCenterTop.setImageURI(resultUri);

            }
        }
    }


    /**
     * 开启图片裁剪库
     *
     * @param uri
     */
    private void startCrop(@NonNull Uri uri) {

        UCrop uCrop = UCrop.of(uri, Uri.fromFile(new File(getCacheDir(), "SampleCropImage.jpg")));
        //初始化UCrop配置
        UCrop.Options options = new UCrop.Options();
        //设置裁剪图片可操作的手势
        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
        //是否隐藏底部容器，默认显示
        options.setHideBottomControls(false);
        //设置toolbar颜色
        options.setToolbarColor(ActivityCompat.getColor(SkinListActivity.this, R.color.red));
        //设置状态栏颜色
        options.setStatusBarColor(ActivityCompat.getColor(SkinListActivity.this, R.color.red));
        //是否能调整裁剪框
        options.setFreeStyleCropEnabled(true);
        //UCrop配置
        uCrop.withOptions(options);

        uCrop.start(SkinListActivity.this);
    }


    /**
     * 打开系统拍照的方法
     */
    private void doCameraAction() {
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        tempUri = Uri.fromFile(new File(Environment
                .getExternalStorageDirectory(), "teakpic.jpg"));
        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
        startActivityForResult(openCameraIntent, CAMERA_REQUEST_CODE);

    }

    /**
     * 弹出相册或者是拍照的对话框
     */
    private void showPopUpWindow() {
        view = View.inflate(this, R.layout.pop_choose_pic, null);
        tvCamera = (TextView) view.findViewById(R.id.tv_camera);
        tvPic = (TextView) view.findViewById(R.id.tv_pic);
        tvCancel = (TextView) view.findViewById(R.id.tv_cancel);
        tvCamera.setOnClickListener(this);
        tvPic.setOnClickListener(this);
        tvCancel.setOnClickListener(this);
        popupWindow = new PopupWindow(view,
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        backgroundAlpha(this, 0.3f);
        popupWindow.setAnimationStyle(R.style.pop_common_style);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(SkinListActivity.this, 1.0f);
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow = null;
                    view = null;
                }
            }
        });
        popupWindow.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM,
                0, 0);
    }

    /**
     * 改变屏幕透明度 方法
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(Activity activity, float bgAlpha) {
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = bgAlpha;
        activity.getWindow().setAttributes(lp);
    }


    /**
     * 解决小米手机上获取图片路径为null的情况
     *
     * @param intent
     * @return
     */
    public Uri geturi(android.content.Intent intent) {
        Uri uri = intent.getData();
        String type = intent.getType();
        if (uri.getScheme().equals("file") && (type.contains("image/*"))) {
            String path = uri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr = getContentResolver();
                StringBuffer buff = new StringBuffer();
                buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=")
                        .append("'" + path + "'").append(")");
                Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        new String[]{MediaStore.Images.ImageColumns._ID},
                        buff.toString(), null, null);
                int index = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                    // set _id value
                    index = cur.getInt(index);
                }
                if (index == 0) {
                    // do nothing
                } else {
                    Uri uri_temp = Uri.parse("content://media/external/images/media/" + index);
                    if (uri_temp != null) {
                        uri = uri_temp;
                    }
                }
            }
        }
        return uri;
    }


    /**
     * 保存文件
     *
     * @param bm
     * @param fileName
     * @throws IOException
     */
    public void saveFile(Bitmap bm, String fileName) throws IOException {
        String path = getSDPath() + "/goldupload/";
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }

        File myCaptureFile = new File(path + fileName);
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.PNG, 100, bos);
        bos.flush();
        bos.close();
    }

    public String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
        } else {
            sdDir = getFilesDir();
        }
        return sdDir.toString();
    }
}
